<template>
  <div class="citylist">
    <div class="citylist-one">
      <van-icon name="arrow-left" @click="$router.go(-1)" />
      <h3>城市选择</h3>
      <span></span>
    </div>

    <van-index-bar :sticky="false" :index-list="az">
      <div v-for="(v, i) in citylist" :key="i">
        <van-index-anchor :index="v.title" />
        <van-cell
          v-for="(item, index) in v.children"
          :key="index"
          :title="item.label"
          @click="indexChange(item)"
        />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
export default {
  data() {
    return {
      citylist: [],
      az: [],
    };
  },
  methods: {
    indexChange(item) {
      window.localStorage.setItem("cityId", item.value);
      window.localStorage.setItem("city", item.label);
      this.$router.go(-1);
    },
  },

  created() {
    this.$http.get("/area/city?level=1").then((res) => {
      let city1 = res.data.body;
      let city2 = [...city1]; //过滤出来a-z用的
      let A_Z = city2.map((v) => {
        return v.short.slice(0, 1).toUpperCase();
      });
      let set = [...new Set(A_Z)];
      let a_z = set.sort(); //首字母组成的数组
      let indexList = [...a_z];
      this.az = indexList;
      a_z.forEach((v, i) => {
        let arr = city1.filter((item) => {
          return item.short.slice(0, 1).toUpperCase() === v;
        });
        a_z[i] = {
          title: v,
          children: [...arr],
        };
      });
      this.citylist = a_z;
      console.log(this.citylist);
    });
  },
};
</script>

<style>
.citylist {
  width: 100%;
  height: 100%;
  position: relative;
}
.citylist-one {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  background: #e6e6e6;
  font-size: 16px;
  position: sticky;
  top: 0;
}
</style>